package cn.usbtg.common.idmanager;

import java.util.ArrayList;
import java.util.List;

/**
 * 生成器
 */
public class BtgIdGenerater implements IdGenerater {
    private String name; //生成器名称
    private List<Formater> formaters = new ArrayList<Formater>(); //格式化器
    private AfterGeneraterReview afterGeneraterReview;//id生成后预览处理逻辑

    public BtgIdGenerater(String name) {
        this.name = name;
    }

    @Override
    public String last() {
        StringBuilder lastId = new StringBuilder();
        for (Formater formater : formaters) {
            lastId.append(formater.last());
        }
        return lastId.toString();
    }

    @Override
    public String next(Object... params) {
        return generateResult(afterGeneraterReview, params);
    }

    @Override
    public String next(AfterGeneraterReview afterGeneraterReview, Object... params) {
        return generateResult(afterGeneraterReview, params);
    }

    private String generateResult(AfterGeneraterReview afterGeneraterReview, Object... params) {
        List<String> formaterResults = new ArrayList<String>();//预生成的format result
        for (Formater formater : formaters) {
            formaterResults.add(formater.next(params));
        }

        /*
            根据是否使用预算结果决定是否重新生成
         */
        boolean isUse = true;

        if (null != afterGeneraterReview) {
            isUse = afterGeneraterReview.intercept(formaters, formaterResults);
        }

        StringBuilder sbId = new StringBuilder();
        if (isUse) {
            for (String formatResult : formaterResults) {
                sbId.append(formatResult);
            }
        } else {
            for (Formater formater : formaters) {
                sbId.append(formater.next(params));
            }
        }
        return sbId.toString();
    }

    /**
     * 添加格式化器
     *
     * @param formater 格式化器
     */
    @Override
    public void addFormater(Formater formater) {
        this.formaters.add(formater);
    }

    @Override
    public String getName() {
        return name;
    }

    @Override
    public void setName(String name) {
        this.name = name;
    }

    @Override
    public List<Formater> getFormaters() {
        return formaters;
    }

    @Override
    public void setFormaters(List<Formater> formaters) {
        this.formaters = formaters;
    }

    @Override
    public AfterGeneraterReview getAfterGeneraterReview() {
        return afterGeneraterReview;
    }

    @Override
    public void setAfterGeneraterReview(AfterGeneraterReview afterGeneraterReview) {
        this.afterGeneraterReview = afterGeneraterReview;
    }
}